package com.comac.tasks.manager.app.mq.listener;

import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.Message;
import com.comac.mom.simpleintegration.mq.BaseMessageListener;
import com.comac.tasks.manager.app.domain.gateway.TasksManagerGateway;
import com.comac.tasks.manager.app.dto.TasksManagerBatchInsertDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 注解指定订阅的主题
 *
 * @author wfb
 */
@Component(value = "TASKS-MANAGER-INSERT")
@Slf4j
public class TasksManagerInsertListener extends BaseMessageListener {

    @Autowired
    private TasksManagerGateway tasksManagerGateway;

    @Override
    public Action consume(Message message) {
        log.info("进入消费的方法，开始消费》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》");
        log.info("consume start, message={}, body = {}", message);
        TasksManagerBatchInsertDTO batchInsertDTO = null;
        try {
            batchInsertDTO = deserialize(message, TasksManagerBatchInsertDTO.class);
            log.info(" batchInsertDTO = {}", message);
            if (null == batchInsertDTO) {
                log.warn("TasksManagerListener,deserialize batchInsertDTO is null,ReconsumeLater");
                throw new BizException("batchInsertDTO，消息body为空");
            }
            log.info("TasksManagerListener,batchInsertDTO:{}", JSONObject.toJSONString(batchInsertDTO));
            if (batchInsertDTO.getTasksManagerDTOS().isEmpty()) {
                log.warn("TasksManagerListener,deserialize batchInsertDTO.getTasksManagerDTOS() is null,ReconsumeLater");
                throw new BizException("batchInsertDTO，消息body为空");
            }
            tasksManagerGateway.batchInsert(batchInsertDTO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("mq消费消息失败");
            log.error("mqConsume error msg:" + e.toString());
            log.error("mqConsume stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("新增待办消息mq消费消息失败");
        }

        return Action.CommitMessage;
    }
}
